/**
 * K3玩法
 * Lion @2018.01.14
 */
$(function () {
	codeKeyList = codeKeyList['TSK3-']['K3|'];
	console.log(codeKeyList);
	var playTips = {
			'HZ':'猜3个开奖号相加的和，3-10为小，11-18为大。赔率<font class="tag_pc_bonus"></font>倍。',
			'STHTX':'对所有相同的三个号码(111、222、333、444、555、666)进行投注，任意号码开出，即为中奖。赔率<font class="tag_pc_bonus"></font>倍。',
			'STHDX':'对相同的三个号码(111、222、333、444、555、666)中的任意一个或多个进行投注，所选号码开出，即为中奖。赔率<font class="tag_pc_bonus"></font>倍。',
			'SBTH':'从1-6中任选3个或多个号码,所选号码与开奖号码的3个号码相同,即为中奖。赔率<font class="tag_pc_bonus"></font>倍。',
			'SLHTX':'对所有的3个相连号码(123、234、345、456)进行投注，任意号码开出，即为中奖。赔率<font class="tag_pc_bonus"></font>倍。',
			'ETHFX':'从11-66中任选1个或多个号码，选号与奖号(包含11-66，不限顺序)相同，即为中奖（不含豹子）。赔率<font class="tag_pc_bonus"></font>倍。',
			'ETHDX':'选择1对相同号码和1个不同号码投注，选号与奖号相同，即为中奖。赔率<font class="tag_pc_bonus"></font>倍。',
			'EBTH':'从1-6中任选2个或多个号码，所选号码与开奖号码任意2个号码相同，即为中奖。赔率<font class="tag_pc_bonus"></font>倍。',
	};
	//玩法切换
	layui.use('element',function(){
        var element = layui.element;
        element.tab({
            headerElem: '#lottery>li' //指定tab头元素项
            ,bodyElem: '#lotteryc>.lotteryshow' //指定tab主体元素项
        });
    })
    // 获取和值的赔率区间
	var oddsSort = [];
	// 玩法类型代码
    var type_code = '';
    // 所有和值玩法的赔率容器数组
	var hz_play   = {};
	$('.tag_k3_play_type li').on('click', '', function (){
		type_code = $(this).attr('ami');
		$('#id_play_tips').html(playTips[type_code]);
		var tmpOdds = '';
		if(type_code == 'HZ'){
			tmpOdds = he_peilv;
		}else{
			tmpOdds = codeKeyList[type_code].odds;
		}
		$('.tag_pc_bonus').html(tmpOdds);
	})
	type_code = type_code ? type_code : $('.tag_k3_play_type li:eq(0)').attr('ami');
	if(type_code == 'HZ'){
		// 和值是多赔率玩法，这里手动整理赔率信息，准备展示
		$.each(codeKeyList, function (i, v){
			if(i.substring(0,2) == 'HZ'){
				v.foll_title = v.foll_title.replace('和值', '');
				hz_play[i] = v;
				oddsSort.push(v.odds);
			}
		})
	}
	// 将用户的赔率信息更新到页面展示
	$.each($('.tag_with_odds'), function (i, v){
		$.each(hz_play, function (i1, v1){
			if($(v).attr('ami') == v1.foll_title){
				$(v).html('赔' + v1.odds);
				// 跳出当前循环，准备下一次
				return false;
			}
		})
	})
	
	oddsSort = oddsSort.sort(function(a,b){
		return a-b;
	});
	var he_peilv = oddsSort.shift() + '~' + oddsSort.pop();
	$('.tag_pc_bonus').html(he_peilv);
	
	
	//全局金额,默认0
	var count = 0;
	var sthdxcount = 0;
	var ethfxcount = 0;
    var ethdxcount = 0;
    
	//合值玩法
	$('.he').click(function(){

		//先判断此元素的父级是否被选中.选中再次点击则取消选中并删除掉选项
		var obj = $(this);
		var id = obj.data('id');
		if(obj.parent('li').hasClass('active'))
		{
            obj.parent('li').removeClass('active');
			var cn = $(".checkedList table tbody tr[data-code='"+id+"']");
			cn.remove();
			acount(0);
			amountmoney();
			return;
		}else
		{
			obj.parent('li').addClass('active');
			$('.checkedList table tbody').append('<tr data-id="和值" data-code="'+id+'" data-num="1"><td><i class="order_type">[和值] '+id+'</i></td>' 
			+'<td><span class="order_zhushu">总共 <i class="order_num c_red">1</i>注</span></td> <td><i class="order_price">'
              +'每注<input class="eachPrice" type="text" value="" />元'
             +'</i></td> <td><i class="c_3"><span class="hide_this">'
                 +'可中金额：<i class="orderMoney c_red">0.00</i>元'
               +' </span></i></td> <td><i class="orderCancel">删除</i></td></tr>');
			acount();
		}

	});

	//三同号玩法
	$('.sth').click(function () {
        var obj = $(this);
        var id = obj.data('id');
        if(obj.parent('li').hasClass('active'))
        {
            obj.parent('li').removeClass('active');
            var cn = $(".checkedList table tbody tr[data-code='"+id+"']");
            cn.remove();
            acount(0);
            return;
        }else
        {
            obj.parent('li').addClass('active');
            $('.checkedList table tbody').append('<tr data-id="三同号通选" data-code="'+id+'" data-num="1"><td><i class="order_type">[三同号通选] '+id+'</i></td>'
                +'<td><span class="order_zhushu">总共 <i class="order_num c_red">1</i>注</span></td> <td><i class="order_price">'
                +'每注<input class="eachPrice" type="text" value="" />元'
                +'</i></td> <td><i class="c_3"><span class="hide_this">'
                +'可中金额：<i class="orderMoney c_red">0.00</i>元'
                +' </span></i></td> <td><i class="orderCancel">删除</i></td></tr>');
            acount();
        }
    });

	//三同号单选
	$('.sthdx').click(function () {
		var obj = $(this);
        var id = obj.data('id');

		if(obj.parent('li').hasClass('active'))
		{ 
            obj.parent('li').removeClass('active');
            sthdxcount = sthdxcount - 1;
		}else
		{
            obj.parent('li').addClass('active');
            sthdxcount += 1;
		}
        $('.sthdxs').find('em:first-child').html(sthdxcount);
    });

	//三同号单选选中处理
	$('#sthdx').click(function(){
       
        var obj = $(this);
		var id = obj.data('id');
        var basic = "";
        $('.sthdx').each(function(){
            if($(this).parent('li').hasClass('active'))
            {   
                basic += $(this).html()+",";
                $(this).parent('li').removeClass('active');
            }
        });
        if(basic == '')
        {
            layer.alert('号码选择不完整，请重新选择', {
                title: '温馨提示'
            })
            return;
        }

        basic = basic.substring(0, basic.lastIndexOf(','));
        $('.checkedList table tbody').append('<tr data-id="三同号单选" data-code="'+basic+'" data-num="'+sthdxcount+'"><td><i class="order_type">[三同号单选] '+basic+'</i></td>'
            +'<td><span class="order_zhushu">总共 <i class="order_num c_red">'+sthdxcount+'</i>注</span></td> <td><i class="order_price">'
            +'每注<input class="eachPrice" type="text" value="" />元'
            +'</i></td> <td><i class="c_3"><span class="hide_this">'
            +'可中金额：<i class="orderMoney c_red">0.00</i>元'
            +' </span></i></td> <td><i class="orderCancel">删除</i></td></tr>');
        $('.sthdxs').find('em:first-child').html('0');
        sthdxcount = 0;
        acount();
	});

	//三不同号玩法
	$('.sbth').click(function(){
        var obj = $(this);
        var id = obj.data('id');
        if(obj.parent('li').hasClass('active'))
        {
            obj.parent('li').removeClass('active');
            sbth();
            return;
        }else
        {
            obj.parent('li').addClass('active');
            sbth();
        }
	});
	//三不同号选中处理
	$('#sbth .ClickShade').click(function(){
		var basic = "";
		$('.sbth').each(function(){
            if($(this).parent('li').hasClass('active'))
            {
                basic += $(this).html() + ",";
                $(this).parent('li').removeClass('active');
            }
		});
        basic = basic.substring(0, basic.lastIndexOf(','));
        var num = 0;
        $.ajaxSetup({
            async : false
        });
        $.post(ct3,{str:basic,num:3},function(data){
            num += parseInt(data);
        });
        $('.checkedList table tbody').append('<tr data-id="三不同号" data-code="'+basic+'"><td><i class="order_type">[三不同号] '+basic+'</i></td>'
            +'<td><span class="order_zhushu">总共 <i class="order_num c_red">'+num+'</i>注</span></td> <td><i class="order_price">'
            +'每注<input class="eachPrice" type="text" value="" />元'
            +'</i></td> <td><i class="c_3"><span class="hide_this">'
            +'可中金额：<i class="orderMoney c_red">0.00</i>元'
            +' </span></i></td> <td><i class="orderCancel">删除</i></td></tr>');
		acount();
		$("#sbth em").html("0");

	});

    //三连号通选玩法
    $('.slhtx').click(function(){
        var obj = $(this);
        var id = obj.data('id');
        if(obj.parent('li').hasClass('active'))
        {
            obj.parent('li').removeClass('active');
            var cn = $(".checkedList table tbody tr[data-id='"+id+"']");
            cn.remove();
            acount();
            amountmoney();
            return;
        }else
        {
            obj.parent('li').addClass('active');
            $('.checkedList table tbody').append('<tr data-id="三连号通选" data-code="'+id+'"><td><i class="order_type">[三连号通选] '+id+'</i></td>'
                +'<td><span class="order_zhushu">总共 <i class="order_num c_red">1</i>注</span></td> <td><i class="order_price">'
                +'每注<input class="eachPrice" type="text" value="" />元'
                +'</i></td> <td><i class="c_3"><span class="hide_this">'
                +'可中金额：<i class="orderMoney c_red">0.00</i>元'
                +' </span></i></td> <td><i class="orderCancel">删除</i></td></tr>');
            acount();

        }

    });

    //二同号复选玩法
    $('.ethfx').click(function () {
        var obj = $(this);
        var id = obj.data('id');
        if(obj.parent('li').hasClass('active'))
        {
            obj.parent('li').removeClass('active');
            ethfxcount -= 1;
            return;
        }else
        {
            obj.parent('li').addClass('active');
            ethfxcount += 1;
        }
        $('#ethfx').find('em:first-child').html(ethfxcount);
    });
    //二同号复选确认处理
    $('#ethfx .ClickShade').click(function(){
        var basic = "";
        $('.ethfx').each(function(){
            if($(this).parent('li').hasClass('active'))
            {
                basic += $(this).html() + " ";
                $(this).parent('li').removeClass('active');
            }
        });

        $('.checkedList table tbody').append('<tr data-id="二同号复选" data-code="'+basic+'"><td><i class="order_type">[二同号复选] '+basic+'</i></td>'
            +'<td><span class="order_zhushu">总共 <i class="order_num c_red">'+ethfxcount+'</i>注</span></td> <td><i class="order_price">'
            +'每注<input class="eachPrice" type="text" value="" />元'
            +'</i></td> <td><i class="c_3"><span class="hide_this">'
            +'可中金额：<i class="orderMoney c_red">0.00</i>元'
            +' </span></i></td> <td><i class="orderCancel">删除</i></td></tr>');
        acount();
        $("#ethfx em").html("0");
    });
    
    //二同号单选
    $('.ethdx').click(function () {
        var obj = $(this);
        var id = obj.data('id');
        //获取对应位置
        var i = obj.index('.checkNumber ul .ethdx') % 6;
        var type = obj.parents('ul').data('type');
        obj.parent().parent().siblings('ul').find('li').eq(i).removeClass('active');
        if(obj.parent('li').hasClass('active'))
        {
            obj.parent('li').removeClass('active');
        }else
        {
            obj.parent('li').addClass('active');
        } 
        var one = $('.layui-show .checkNumber ul').eq(0).find('.active').length;
        var two = $('.layui-show .checkNumber ul').eq(1).find('.active').length;
        ethdxcount = parseInt(one) * parseInt(two);
        $('#ethdx').find('em:first-child').html(ethdxcount);
    });
    //二同号单选确认选中
    $('#ethdx .ClickShade').click(function(){

        var basic1 = "";
        var active = $('.layui-show .checkNumber ul').eq(0).find('.active');
        active.each(function(){
            basic1 += $(this).find('.ethdx').html() + " ";
        });

        var basic2 = "";
        var active2 = $('.layui-show .checkNumber ul').eq(1).find('.active');
        active2.each(function(){
            basic2 += $(this).find('.ethdx').html() + " ";
        });
        
        var basic = basic1 + "," + basic2;
        
        var one = $('.layui-show .checkNumber ul').eq(0).find('.active').length;
        var two = $('.layui-show .checkNumber ul').eq(1).find('.active').length;
        num = parseInt(one) * parseInt(two);
        $('.layui-show .checkNumber ul').find(".active").removeClass('active');
        $('.checkedList table tbody').append('<tr data-id="二同号单选" data-code="'+basic+'"><td><i class="order_type">[二同号单选] '+basic+'</i></td>'
            +'<td><span class="order_zhushu">总共 <i class="order_num c_red">'+num+'</i>注</span></td> <td><i class="order_price">'
            +'每注<input class="eachPrice" type="text" value="" />元'
            +'</i></td> <td><i class="c_3"><span class="hide_this">'
            +'可中金额：<i class="orderMoney c_red">0.00</i>元'
            +' </span></i></td> <td><i class="orderCancel">删除</i></td></tr>');
        acount();
        $(".checkNumber li").removeClass('active');
        $('#ethdx em').html("0");
    });
    //二不同号
    $('.ebth').click(function () {
        var obj = $(this);
        var id = obj.data('id');
        if(obj.parent('li').hasClass('active'))
        {
            obj.parent('li').removeClass('active');
            var basic = "";
            $('.ebth').each(function(){
                if($(this).parent('li').hasClass('active'))
                {
                    basic += $(this).html() + ",";
                }
            });
            basic = basic.substring(0, basic.lastIndexOf(','));
            $.post(ct2,{str:basic,num:2},function(data){
                $('#ebth').find('em:first-child').html(data);
            });
        }else
        {
            obj.parent('li').addClass('active');
            var basic = "";
            $('.ebth').each(function(){
                if($(this).parent('li').hasClass('active'))
                {
                    basic += $(this).html() + ",";
                }
            });
            basic = basic.substring(0, basic.lastIndexOf(','));
            $.post(ct2,{str:basic,num:2},function(data){
                $('#ebth').find('em:first-child').html(data);
            });
        }
        $('#ethdx').find('em:first-child').html(ethdxcount);
    });
    $('#ebth .ClickShade').click(function(){
        var basic = "";
        $('.ebth').each(function(){
            if($(this).parent('li').hasClass('active'))
            {
                basic += $(this).html() + ",";
                $(this).parent('li').removeClass('active');
            }
        });
        basic = basic.substring(0, basic.lastIndexOf(','));
        var num = 0;
        $.ajaxSetup({
            async : false
        });
        $.post(ct2,{str:basic,num:2},function(data){
            num += parseInt(data);
        });
        $('.checkedList table tbody').append('<tr data-id="二不同号" data-code="'+basic+'"><td><i class="order_type">[二不同号] '+basic+'</i></td>'
            +'<td><span class="order_zhushu">总共 <i class="order_num c_red">'+num+'</i>注</span></td> <td><i class="order_price">'
            +'每注<input class="eachPrice" type="text" value="" />元'
            +'</i></td> <td><i class="c_3"><span class="hide_this">'
            +'可中金额：<i class="orderMoney c_red">0.00</i>元'
            +' </span></i></td> <td><i class="orderCancel">删除</i></td></tr>');
        acount();
        $('#ebth em').html("0");
    });
	//重新穷举
	function sbth()
	{
        var basic = "";
        $('.sbth').each(function(){
            if($(this).parent('li').hasClass('active'))
            {
                basic += $(this).html() + ",";
            }
        });
        basic = basic.substring(0, basic.lastIndexOf(','));
        $.post(ct3,{str:basic,num:3},function(data){
            $('#sbth').find('em:first-child').html(data);
        });
	}

	//通用计算此次下注的费用
    $('.checkedList').on("input","table tbody tr td .eachPrice",function(){
    	//每次输入框值变化就循环计算总投注金额
    	amountmoney();
        var obj = $(this);
        if(isInteger(obj.val()) != true)
        {
            obj.val('0');
            return;
        }
        if(obj.val() != '')
        {
            var parent = obj.parents('tr');
            var id = parent.data('id');
            var code = parent.data('code');
            var num = parent.data('num');
            var money = obj.val();
            var ss = parent.find('.orderMoney').html();
            $.post(curl,{id:id,code:code,money:money},function(data){
                parent.find('.orderMoney').html(data);
                amountmoney();
            })
        }
    });

    //用户点击删除的时候,清除投注tr与li的选中状态
    $('.checkedList').on("click","table tbody tr td .orderCancel",function(){
        var obj = $(this);
        var id = obj.parents('tr').data('code');
        var data =  $('.checkNumber').find('a[data-id="'+id+'"]');
        data.parents('li').removeClass('active');
        obj.parents('tr').remove();
        amountmoney();
        acount();
    });

    //当用户点击提交购彩的时候
    $('#lj').click(function(){
    	if ($.isEmptyObject(k3InfoStopTime)){
    		 layer.alert('暂未开始投注', {
                 title: '温馨提示'
               })
               return;
    	}
        $('.textarea').find('p').html('');
        var content = $(".checkedList").find("tr");
      
        if(content.length == 0)
        {
            layer.alert('请至少选择一注投注号码', {
              title: '温馨提示'
            })
            return;
        }

        //判断是否未填写金额的投注。
        var result = true; 
        var countmoney = 0;
        content.each(function(i,k){
            var eachPrice = $(k).find('.eachPrice').val();
            var total = $(k).find('.order_num').html();
            if(eachPrice == false)
            {
                layer.alert('您有号码未设置金额，请核对后投注。', {
                  title: '温馨提示'
                })
                result = false;
            }else{
                //获取用户所选的玩法
                var con = $(k).find('.order_type').html();
                var app = $('.textarea').find('p');
                app.append(con+'<br>');
                //获取彩种名称和价格
                var title = $('.betLogo').find('h2').html();
                var ctmoney = parseInt(eachPrice) * parseInt(total);
                countmoney += ctmoney;
                $('#title').html(title);
                $('#countmoney').html(countmoney);
            }
        });
        if(!result) return; 
        
        $('#confirm').show();
    });

    $('#k3sub').click(function(){
        var a = $('#tid').val();
        var BettingData = [];
        var BettingCount = [];
        var amount = 0;
        $('.checkedList').find('tr').each(function(i,k){
            var obj = $(this);
            var id = obj.data('id');
            if(id == '三同号单选')
            {
                var s = obj.find('.order_type').html();
                var ss = s.substring(8);
                var code = ss;
            }else{
                var code = obj.data('code');
            }
            var type = obj.data('id');
            var total = obj.find('.order_num').html();
            var money = obj.find('.eachPrice').val();
            
            var countmoney = parseInt(total) * parseInt(money);
            
          //  BettingData[i] = '{"play_detail_code":"'+a+'","betting_number":"'+code+'","betting_count":"1","betting_money":"'+countmoney+'","betting_type":"'+type+'","betting_point":"1","betting_model":"1","betting_issuseNo":"'+new Date()+'","graduation_count":"1"}';
            
            BettingData.push($.parseJSON('{"play_detail_code":"'+a+'","betting_number":"'+code+'","betting_count":"1","betting_money":"'+countmoney+'","betting_type":"'+type+'","betting_point":"1","betting_model":"1","betting_issuseNo":"'+new Date()+'","graduation_count":"1"}'));
            BettingCount.push(code);
            amount += parseInt(money);
        });
   
        //alert(BettingData);

        var cid = $('#tid').val();
        var iid = $('#period').val();
       
        if(cid == '' || iid == '')
        {
            layer.alert('网络错误,请刷新重试!', {
              title: '温馨提示'
            })
            return;
        }
      
        var datas = {
            cid:cid,
            iid:iid,
            BettingCount:BettingCount,
            amount:amount,
            BettingData:BettingData
        };
        console.log(datas);
        $.post(orderurl,datas,function(data){
            if (data.status == true){
                layer.alert(data.msg, {
                  title: '温馨提示'
                },  
                function (index, item) {  
                    //layer.close(index);  
                    location.reload();  
                });
                return;
            }else{
                layer.alert(data.msg, {
                  title: '温馨提示'
                });
                return;
            } 
        },'json');
    });
    $('.layermend,#qx').click(function(){
        $('#confirm').hide();
    });
	function acount()
	{
        var count = 0;
        $('.order_num').each(function(){
            count += parseInt($(this).html());
        });
		$('#BetCount').find('em:first-child').html(count);
	}

	function amountmoney()
	{
		var money = 0;
        
		$('.eachPrice').each(function(){
            var obj = $(this);
            var num = parseInt($(obj).parents('tr').find('.order_num').html());
            var sum = parseInt($(this).val())||0;
			if(sum != '')
			{
				money += num * sum;
			}
		});
		$('.money').html(money);
	}

	function isInteger(obj) {
		if(obj%1 === 0)
		{
			return true;
		}else{
			return false;
		}
	}
	
	//btnNav切换	
	var len = $(".betNav li").length;
	var width = $(".betNav li")[0].offsetWidth;
	var index = len-6;
	var n =0;
	//首次加载通过判断len来是否禁止左右按钮点击
	if(len<6){
		$(".betNavtab.left").addClass("betNavtabClass");
		$(".betNavtab.right").addClass("betNavtabClass");
	}else{
		//首次加载自动定位到当前彩种

		
		var liData   = $('#id_lottNav li');
		var val      = 1;
		$.each(liData, function (i, v){
			if($(v).hasClass('active')){
				val = val + i;
			}
		})

		if(val>6){
			$(".betNav").css({
				"transform":"translateX(-"+(val-6)*width+"px)"
			})
			n = val-6;
		}
		//左右按钮切换
		$(".betNavtab.left").click(function(){
			$(".betNavtab.right").removeClass("betNavtabClass");
			if(n>0){
				n--;
				$(".betNav").css({
					"transform":"translateX(-"+n*width+"px)"
				})
			}else{
				$(this).addClass("betNavtabClass");
				layer.msg("已经到顶了");
			}
		})
		$(".betNavtab.right").click(function(){
			$(".betNavtab.left").removeClass("betNavtabClass");
			if(n<index){
				n++;
				$(".betNav").css({
					"transform":"translateX(-"+n*width+"px)"
				})
			}else{
				$(this).addClass("betNavtabClass");
				layer.msg("已经到底了");
			}
		})
	}
})

